package com.lyl.label.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyl.label.dao.LabelGroupDao;
import com.lyl.label.model.dto.LabelGroupDTO;
import com.lyl.label.model.entity.LabelGroup;
import com.lyl.label.model.vo.LabelTreeVO;
import com.lyl.label.service.LabelGroupService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 标签组表(LabelGroup)表服务实现类
 *
 * @author makejava
 * @since 2022-06-20 21:21:40
 */
@Service("labelGroupService")
@RequiredArgsConstructor
public class LabelGroupServiceImpl extends ServiceImpl<LabelGroupDao, LabelGroup> implements LabelGroupService {
    private final LabelGroupDao labelGroupDao;

    @Override
    public List<LabelGroupDTO> listByLevel(Integer level) {
        if (level < 0){
            return ListUtil.empty();
        }
        List<Integer> levelList = generalLevelList(level);
        return labelGroupDao.listByLevel(levelList);
    }

    private List<Integer> generalLevelList(Integer level) {
        return Stream.iterate(0, n -> n + 1)
                .limit(level + 1)
                .collect(Collectors.toList());
    }

    @Override
    public List<LabelGroupDTO> listByLevel(Integer level, String keyword) {
        return labelGroupDao.listByLevelAndKeyword(generalLevelList(level),keyword);
    }

    @Override
    public List<LabelTreeVO> labelTree(String labelName) {
        return getTree(labelGroupDao.labelTree(labelName));
    }

    public List<LabelTreeVO> getTree(List<LabelTreeVO> list){
        if (CollUtil.isEmpty(list)){
            return ListUtil.empty();
        }
        Map<Integer, List<LabelTreeVO>> levelMap = list.stream().collect(Collectors.groupingBy(LabelTreeVO::getLevel));
        List<Integer> levelList = levelMap.keySet().stream().sorted().collect(Collectors.toList());
        while (levelList.size() > 0){
            Integer level = levelList.remove(levelList.size() - 1);
            List<LabelTreeVO> childLabels = levelMap.getOrDefault(level, ListUtil.empty());
            List<LabelTreeVO> labelList = levelMap.getOrDefault(level - 1, ListUtil.empty());
            if (CollUtil.isEmpty(labelList)){
                return childLabels;
            }
            Map<Long, List<LabelTreeVO>> childMap = childLabels.stream().collect(Collectors.groupingBy(LabelTreeVO::getParentId));
            labelList.forEach(label -> label.setChildList(childMap.getOrDefault(label.getId(),ListUtil.empty())));
        }
        return list;
    }
}
